package com.qf.elasticsearch.query.impl;

import com.qf.elasticsearch.query.HighLightService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * create by 郑大仙丶
 * 2019/11/21 23:55
 */
@Service
public class HighLightServiceImpl implements HighLightService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public List<Map<String, Object>> highLightQuery(String index,String type,String field) throws IOException {
        //1. 创建查询request
        SearchRequest request = new SearchRequest(index);
        request.types(type);
        //2. 设置查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("smsContent","中国移动"));
        //高亮设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field(field);
        highlightBuilder.preTags("<b><font color='red'>");
        highlightBuilder.postTags("</font></b>");
        highlightBuilder.fragmentSize(107);
        builder.highlighter(highlightBuilder);
        request.source(builder);
        //3. 执行查询
        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        //4. 封装结果
        SearchHit[] hits = resp.getHits().getHits();
        List<Map<String, Object>> result = new ArrayList<>();
        for (SearchHit hit : hits) {
            result.add(hit.getSourceAsMap());
            int length = hit.getSourceAsMap().get(field).toString().length();
            System.out.println(length);
            Text[] texts = hit.getHighlightFields().get(field).getFragments();
            System.out.println(texts[0].toString().length());
            System.out.println(Arrays.toString(texts));


        }
        //5. 返回
        return result;
    }
}
